package cn.turboinfo.fuyang.api.gateway.web.config

import cn.turboinfo.fuyang.api.provider.framework.spring.ConverterCollection
import net.sunshow.toolkit.core.base.enums.converter.BaseEnumConverter
import org.springframework.beans.factory.support.BeanDefinitionBuilder
import org.springframework.beans.factory.support.BeanDefinitionRegistry
import org.springframework.context.EnvironmentAware
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar
import org.springframework.core.env.Environment
import org.springframework.core.type.AnnotationMetadata
import org.springframework.core.type.filter.AssignableTypeFilter

class WebConverterBeanDefinitionRegistrar : ImportBeanDefinitionRegistrar, EnvironmentAware {

    private lateinit var environment: Environment

    private val basePackages = arrayOf(
        "net.sunshow.toolkit.core.base.enums.converter",
        "**.provider.**.repository.database.**.converter",
        "cn.turboinfo.fuyang.api.provider.framework.converter",
    )

    override fun setEnvironment(environment: Environment) {
        this.environment = environment
    }

    override fun registerBeanDefinitions(importingClassMetadata: AnnotationMetadata, registry: BeanDefinitionRegistry) {
        val provider = ClassPathScanningCandidateComponentProvider(false, environment)

        // 查找所有 BaseEnumConverter 的子类
        provider.addIncludeFilter(AssignableTypeFilter(BaseEnumConverter::class.java))

        val collection = ConverterCollection()

        for (basePackage in basePackages) {
            for (beanDefinition in provider.findCandidateComponents(basePackage)) {
                // 逐个添加到 ConverterCollection
                // 调用空构造函数构建实例
                collection.add(
                    Class.forName(beanDefinition.beanClassName).getConstructor().newInstance() as BaseEnumConverter<*>
                )
            }
        }

        // 注册供后续处理
        registry.registerBeanDefinition(
            "defaultWebConverterCollection",
            BeanDefinitionBuilder
                .genericBeanDefinition(
                    ConverterCollection::class.java
                ) {
                    collection
                }
                .beanDefinition
        )

    }

}
